var express = require('express');
var router = express.Router();
let { UserM, shop_list,shop_Cart } = require('../../modules/long')
/* GET home page. */
router.get('/shop_list', async (req, res) => {
  let page = parseInt(req.query.page) || 1; // 默认为第1页
  let limit = parseInt(req.query.limit) || 20; // 默认每页20条
  const skip = (page - 1) * limit;
  let data = await shop_list.find().skip(skip).limit(limit).exec()
  console.log(data);
  res.send({
    code: 200,
    data,
    totalPages: Math.ceil(data / limit),
    currentPage: page,
  })
})

router.get('/shop_cart', async (req, res) => {
  let data = await shop_Cart.find()
  res.send({
    code: 200,
    data,
  })
})

router.post('/addcart', async (req, res) => {
  console.log(req.body.data);
  let a={
    name:req.body.data.name,
    price:req.body.data.price,
    image:req.body.data.image[0],
    num:1,
    isable:false
  }
  await shop_Cart.create(a)
  res.send({
    code: 200,
    msg: '添加成功',
  })

})

router.put('/editcart', async (req, res) => {
  let {id,isable} = req.body
  
  await shop_Cart.updateOne({ _id: id },{$set:{isable:!isable}})
  res.send({
    code: 200,
    msg: '修改成功',
  })
})

router.put('/editnum', async (req, res) => {
  let {id,num} = req.body
  
  await shop_Cart.updateOne({ _id: id },{$set:{num:num}})
  res.send({
    code: 200,
    msg: '修改成功',
  })
})

router.post('/deletecart', async (req, res) => {
  let {id} = req.body
  await shop_Cart.deleteOne({ _id: id })
  res.send({
    code: 200,
    msg: '删除成功',
  })
})
const AlipayFormData = require('alipay-sdk/lib/form').default
const alipaySdk = require('./alipay')


router.post("/pcpay", async (req, res) => {
  let { data } = req.body
  console.log(data)
  const formData = new AlipayFormData()

  formData.setMethod('get');
  // 通过addField增加参数
  // 在用户支付完成之后，支付宝服务器会根据传入的notify_url,以post请求的形式将支付结果作为参数通知到商户系统
  // 支付成功或失败都返回
  formData.addField('returnUrl', "http://127.0.0.1:3000/fan/cheng");//支付成功后返回的页面
  formData.addField('bizContent', {
    out_trade_no: 'e4b0c44278fc1c149afbf4c5396fb92424ae41e4649b834ca495999b7952b854',//订单号 64个字符以内 可包含字母、数字、下划线、且不能重复
    product_code: "FAST_INSTANT_TRADE_PAY",//销售产品码，与支付宝签约的产品码名称，仅支持FAST_INSTANT_TRADE_PAY
    total_amount: 8,// 订单总金额
    subject: '1229',// 订单描述
    body: '34234',// 商品描述
  })
  // 返回promise
  const result = await alipaySdk.exec(
    'alipay.trade.wap.pay',//统一收单下单并支付页面接口,
    {},//api请求的参数（包含 “公共请求参数”和“业务参数”）
    { formData: formData }// result为可以跳转支付链接的url
  )
  // res.json({ url: result })
  res.send({
    code: 200,
    result
  })
})
module.exports = router;
